<template>
  <div id="spaceDetailPage">
    <!-- 空间信息 -->
    <a-flex justify="space-between">
      <h2>{{ space.spaceName }}({{ SPACE_TYPE_MAP[space.spaceType] }})</h2>
      <a-space size="middle">
        <a-button
          v-if="canUploadPicture"
          type="primary"
          :href="`/add_picture?spaceId=${id}`"
          target="_blank"
          >+ 创建图片</a-button
        >
        <a-button
          v-if="canManageSpaceUser"
          type="primary"
          ghost
          :icon="h(TeamOutlined)"
          :href="`/spaceUserManger/${id}`"
          target="_blank"
        >
          成员管理
        </a-button>

        <a-button
          v-if="canManageSpaceUser"
          type="primary"
          ghost
          :icon="h(BarChartOutlined)"
          :href="`/space_analyze?spaceId=${id}`"
          target="_blank"
          >空间分析</a-button
        >
        <a-button v-if="canEditPicture" @click="doBatchEdit">+ 批量编辑</a-button>
        <a-tooltip
          :title="`占用空间：${formatBytes(space?.totalSize)}/${formatBytes(space?.maxSize)}`"
        >
          <a-progress
            type="circle"
            :percent="
              space?.maxSize
                ? ((Number(space.totalSize) * 100) / Number(space.maxSize)).toFixed(1)
                : 0
            "
            :size="42"
          />
        </a-tooltip>
      </a-space>
    </a-flex>
    <div style="margin-bottom: 16px"></div>
    <!-- 搜索 -->
    <PictureSearchForm :onSearch="onSearch" />
    <!-- 跟其他搜索独立 -->
    <a-form-item label="按颜色搜索">
      <color-picker format="hex" @pure-color-change="onColorChange" />
    </a-form-item>
    <div style="margin-bottom: 16px"></div>
    <!-- 图片列表 -->
    <PictureList
      :dataList="dataList"
      :loading="loading"
      :showOp="true"
      :onReload="fetchData"
      :canEdit="canEditPicture"
      :canDelete="canDeletePicture"
    />
    <!-- 分页 -->
    <a-pagination
      style="text-align: right"
      v-model:pageNum="searchParam.pageNum"
      v-model:pageSize="searchParam.pageSize"
      :total="total"
      @change="onPageChange"
    />
  </div>
  <BatchEditPicture
    ref="batchEditPictureRef"
    :spaceId="id"
    :pictureList="dataList"
    :onSuccess="onBatchEditSuccess"
  />
</template>
<script lang="ts" setup>
import { ref, onMounted, h, watch, computed } from 'vue'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController'
import BatchEditPicture from '@/components/BatchEditPicture.vue'
import {
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/api/pictureController'
import { TeamOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { formatBytes } from '@/utils'
import PictureList from '@/components/PictureList.vue'
import { ColorPicker } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import { BarChartOutlined } from '@ant-design/icons-vue'
import { SPACE_PERMISSION_ENUM, SPACE_TYPE_MAP } from '@/constants/space'

const loading = ref(false)
interface Props {
  id: number | string
}
const props = defineProps<Props>()
const space = ref<API.SpaceVO>({})
const dataList = ref<API.SpaceVO[]>([])
const total = ref(0)
//搜索条件
const searchParam = ref<API.SpaceQueryRequest>({
  pageNum: 1,
  pageSize: 15,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (space.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canUploadPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD)
const canEditPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDeletePicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)

const onPageChange = (pageNum: number, pageSize: number) => {
  searchParam.value.pageNum = pageNum
  searchParam.value.pageSize = pageSize
  fetchData()
}
//获取图片列表
async function fetchData() {
  //转换搜索参数
  const params = {
    spaceId: props.id,
    ...searchParam.value,
  }
  loading.value = true
  const res = await listPictureVoByPageUsingPost(params)
  if (res.data.code == 200 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
    loading.value = false
  } else {
    message.error('获取数据失败' + res.data.message)
    loading.value = false
  }
}

//获取空间详情
const fetchSpaceDetail = async () => {
  try {
    const res = await getSpaceVoByIdUsingGet({ id: props.id })
    if (res.data.code === 200 && res.data.data) {
      const data = res.data.data
      space.value = data
    } else {
      message.error('获取空间详情失败或' + res.data.message)
    }
  } catch (err) {
    message.error('获取空间详情失败' + err)
  }
}
// 搜索
const onSearch = (newSearchParams: API.PictureQueryRequest) => {
  console.log('new', newSearchParams)

  searchParam.value = {
    ...searchParam.value,
    ...newSearchParams,
    pageNum: 1,
  }
  console.log('searchparam', searchParam.value)
  fetchData()
}

//按颜色搜索
//获取图片列表
async function onColorChange(color: string) {
  //转换搜索参数
  const params = {
    picColor: color,
    spaceId: props.id,
  }
  loading.value = true
  const res = await searchPictureByColorUsingPost(params)
  if (res.data.code == 200 && res.data.data) {
    dataList.value = res.data.data ?? []
    total.value = res.data.data.length ?? 0
    loading.value = false
  } else {
    message.error('获取数据失败' + res.data.message)
    loading.value = false
  }
}
//打开编辑弹窗
function doBatchEdit() {
  if (batchEditPictureRef.value) {
    batchEditPictureRef.value.openModel()
  }
}

//批量编辑图片
const batchEditPictureRef = ref()
//批量编辑图片成功
const onBatchEditSuccess = () => {
  fetchSpaceDetail()
}
//空间id改变时重新获取数据
watch(
  () => props.id,
  () => {
    fetchData()
    fetchSpaceDetail()
  }
)

//页面加载时获取数据
onMounted(() => {
  fetchSpaceDetail()
  fetchData()
})
</script>
<style scoped>
#spaceDetailPage {
}
</style>

